package com.demo.utils;

public class IPUtils {

    /**
     * 将ipv4地址转换成数字
     * 192.68.11.22
     * @param ip
     * @return
     */
    public static long ipv4ToNum(String ip) {
        String[] ipArr = ip.split("\\.");
        long num = 0L;
        for (int i = 0; i <= 3; i++) {
            long seg = Long.parseLong(ipArr[i]);
            num = num + (seg << ((3 - i) * 8));
        }
        return num;
    }

    /**
     * 将数字转换ipv4地址
     * @param ip
     * @return
     */
    public static String num2Ipv4(long ip) {
        return ((ip >> 24) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                (ip & 0xFF);
    }

    /**
     * 将ipv4地址转换为全写格式
     * 192.68.11.22 => 192.068.011.022
     * @param ipv4
     * @return
     */
    public static String convertIpv4ToFull(String ipv4) {
        String[] parts = ipv4.split("\\.");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < parts.length; i++) {
            sb.append(String.format("%03d", Integer.parseInt(parts[i])));
            if (i < parts.length - 1) {
                sb.append(".");
            }
        }
        return sb.toString();
    }

    /**
     * 将ipv4地址转换为简写格式
     * @param ipv4
     * @return
     */
    public static String convertIpv4ToShort(String ipv4) {
        String[] parts = ipv4.split("\\.");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < parts.length; i++) {
            sb.append(Integer.parseInt(parts[i]));
            if (i < parts.length - 1) {
                sb.append(".");
            }
        }
        return sb.toString();
    }

    /**
     * IP地址检索（二分查找）
     * @param ipInfo IP地址库，开始ip/结束ip/区域编码，ip地址是全写的格式，order by 开始ip asc
     * @param ip 待检索的ip地址
     * @return 数组的下标，如果没有检索到，返回-1
     */
    public static int ipBinarySearch(String[][] ipInfo, String ip) {
        int low = 0;
        int high = ipInfo.length - 1;
        while (low <= high) {
            int mid = (low + high) / 2;
            String startIp = ipInfo[mid][0];
            String endIp = ipInfo[mid][1];
            if (ip.compareTo(startIp) >= 0 && ip.compareTo(endIp) <= 0) {
                return mid;
            } else if (ip.compareTo(startIp) < 0) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        // 未找到
        return -1;
    }
}